package one.deploy.config;

import cn.hutool.core.io.file.FileReader;
import lombok.Builder;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.maven.model.io.xpp3.MavenXpp3Reader;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.Objects;
import java.util.regex.Matcher;

@Slf4j
public class DefaultVersionReader implements IVersionReader {
    @Override
    public String getLast(String lastVersionUrl) {
        Model model;
        if (lastVersionUrl.endsWith("pom.xml")) {
            model = getLastByPom(lastVersionUrl);
        } else {
            model = getLastByFile(lastVersionUrl);
        }
        return Objects.nonNull(model) ? model.getVersion() : StringUtils.EMPTY;
    }

    @Data
    @Builder
    private static class Model {
        private String name;
        private String version;
    }

    private Model getLastByFile(String filePath) {
        try {
            FileReader fileReader = new FileReader(filePath);
            String fileContent = fileReader.readString();
            Matcher matcher = ServiceConfigReader.pattern.matcher(fileContent);
            if (matcher.find()) {
                String result = StringUtils.defaultIfBlank(matcher.group(2), matcher.group(4));
                return Model.builder()
                        .name(result)
                        .version(result)
                        .build();
            }
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        }
        return null;
    }

    private Model getLastByPom(String filePath) {
        FileInputStream fis = null;
        try {
            fis = new FileInputStream(new File(filePath));
            MavenXpp3Reader reader = new MavenXpp3Reader();
            org.apache.maven.model.Model model = reader.read(fis);
            return Model.builder()
                    .name(model.getName())
                    .version(model.getVersion())
                    .build();
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        } finally {
            if (Objects.nonNull(fis)) {
                try {
                    fis.close();
                } catch (IOException e) {
                    log.error(e.getMessage(), e);
                }
            }
        }
        return null;
    }
}
